"""Convert one account in a gnucash xml file to a flat line file.
"""
from datetime import datetime
from decimal import Decimal
import re
import xml.etree.cElementTree as ET
import logging

from obj.flat import ptagvalue

def text_to_decimal(text):
    if text.index('/') != -1:
        p = text.split('/')
        return Decimal(p[0]) / Decimal(p[1])
    else:
        return Decimal(text)


def flat(gnucashname,fout,linetxt):
    guid = None
    tree = ET.parse(gnucashname)
    for acct in tree.getroot()[1].findall('{http://www.gnucash.org/XML/gnc}account'):
        account_name = acct.find('{http://www.gnucash.org/XML/act}name').text
        guid = acct.find('{http://www.gnucash.org/XML/act}id').text

        trns = []  # list of (amount, XML node) for transations modifying account
        for trn in tree.getroot()[1].findall('{http://www.gnucash.org/XML/gnc}transaction'):
            for spl in trn.find('{http://www.gnucash.org/XML/trn}splits').findall('{http://www.gnucash.org/XML/trn}split'):
                act = spl.find('{http://www.gnucash.org/XML/split}account').text
                if act == guid:
                    value = text_to_decimal(spl.find('{http://www.gnucash.org/XML/split}value').text)
                    trns.append( (value, trn) )
        if not trns:
            logging.warning('No transactions found for account %s',account_name)

        for (value, trn) in trns:
            ptagvalue('UNITS', "%.2f" % value, fout)
            ptagvalue('NAME', trn.find('{http://www.gnucash.org/XML/trn}description').text, fout)
            date_gc = trn.find('{http://www.gnucash.org/XML/trn}date-posted/{http://www.gnucash.org/XML/ts}date').text
            dt = datetime.strptime(date_gc, "%Y-%m-%d %H:%M:%S +0000")
            ptagvalue('DTSETTLE', dt.strftime('%Y%m%d%H%M%S[0:GMT]'), fout)
            ptagvalue('ACCTID',account_name,fout) # every line is identified with an Account object through ACCTID key
            # TODO use a better SECID value. Not all accounts are necessarly checking and not all of them are necessarly USD
            ptagvalue('SECID','CURRENT=CHECKING=USD',fout) # every transaction is from/to an Asset which is identified with SECID key
            print >>fout, linetxt # By definition the linetxt is appended as-is at the end of every line

# Every import module needs to have the following
ext='*.gc' # file extension
def path(line):
    """Default directory to look for files from this source"""
    return ['gnucash']
# Help text that can be retrieved with the command line
# import -S=gnucash -HELP
help="""For each account in a gnucash file import all transactions aka split"""